package cn.piaoyi.web.interceptor;

import java.util.Map;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.struts2.ServletActionContext;
import org.apache.struts2.views.util.DefaultUrlHelper;
import org.apache.struts2.views.util.UrlHelper;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;
import cn.piaoyi.comm.Constant;
import cn.piaoyi.web.servlet.AdminSession;
import cn.piaoyi.web.servlet.UserSession;

import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.interceptor.AbstractInterceptor;

public class CartPermissionInterceptor extends AbstractInterceptor {
	/**
	 * Logger for this class
	 */
	private static final Log logger = LogFactory.getLog(CartPermissionInterceptor.class);

	/**
	 *
	 */
	private static final long serialVersionUID = 1857640901215440713L;

	@Override
	public String intercept(ActionInvocation invocation) throws Exception {

		ActionContext ac = invocation.getInvocationContext();
		String actionName = "/" + ac.getName();

		String saction = "";

		Map map = ac.getParameters();
		String[] _saction = (String[]) map.get("action");
		if (_saction != null) {
			saction = _saction[0];
		}
		
		HttpServletRequest request = (HttpServletRequest) ac.get(ServletActionContext.HTTP_REQUEST);
		HttpServletResponse response = (HttpServletResponse) ac.get(ServletActionContext.HTTP_RESPONSE);
		ServletContext servletContext = (ServletContext) ac.get(ServletActionContext.SERVLET_CONTEXT);
		WebApplicationContext wc = WebApplicationContextUtils.getWebApplicationContext(servletContext);
		
		StringBuilder sb = new StringBuilder(request.getServletPath());
		UrlHelper helper = new DefaultUrlHelper();
		helper.buildParametersString(map, sb, "&");
		
		UserSession us = (UserSession) ac.getSession().get(Constant.USER_SESSION_KEY);

		boolean havePermission = true;
		
		if(us.getUid()==0){
			havePermission = false;
		}
		if (havePermission) {
			return invocation.invoke();
		} else {
			if(saction.equalsIgnoreCase("shop")){
				ac.getValueStack().set("tourl", sb.toString());
				ac.getValueStack().set("action", "login");
				return "user_login";
			}else{
				ac.getValueStack().set("tourl", sb.toString());
				ac.getValueStack().set("action", "poplogin");
				return "user_poplogin";
			}
		}
	}
}
